package com.zxl.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.zxl.pojo.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 可以取出第三方授权成功返回的用户信息
     */
    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @PostMapping("register")
    public String register(User user, HttpServletRequest request) {
        // 用户注册，不管是注册用户还是绑定用户，都会拿到用户的唯一标识
        String userId = user.getUsername();// 这里我简单用用户名作为唯一标识，正常情况下应该使用用户主键
        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
        return "注册成功";
    }

    /**
     * 返回所有认证通过的信息
     * @param authentication
     * @return
     */
    @GetMapping("detail")
    public Object getCurrentUser(Authentication authentication) {
        return authentication;
    }

    /**
     * 返回所有认证通过的信息
     * @return
     */
    @GetMapping("my")
    public Object getCurrentUser() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 只返回用户的基本信息
     * @param userDetails
     * @return
     */
    @GetMapping("me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation("查询用户列表")
    public List<User> user(String username, @PageableDefault(page = 1, size = 5, sort = {"age,asc"}) Pageable pageable) {
        List<User> users = new ArrayList<>();
        System.out.println(pageable.getSort().toString());
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    @GetMapping("{id:[0-9]+}")
    @JsonView(User.UserDetailView.class)
    public User user(@ApiParam("用户ID") @PathVariable("id") Integer id) {
        User user = new User();
        user.setId(id);
        user.setUsername("scott");
        return user;
    }

    @PostMapping
    public User create(@RequestBody @Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.toString());
        user.setId(2);
        return user;
    }

    @PutMapping
    public User update(@RequestBody @Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.toString());
        return user;
    }

    @DeleteMapping("{id:[0-9]+}")
    public void delete(@PathVariable Integer id) {
        System.out.println("delete user " + id);
    }
}
